package com.dodo.blog.ui.page.admin;

import com.dodo.blog.model.Role;
import com.dodo.blog.model.Tag;
import com.dodo.blog.server.TagService;
import com.dodo.blog.ui.ajax.Response;
import com.dodo.blog.ui.ajax.annotation.GetModel;
import com.dodo.blog.ui.ajax.annotation.SetModel;
import com.dodo.blog.ui.authorization.Authorized;
import com.dodo.blog.ui.component.composite.FieldSet;
import com.dodo.blog.ui.component.composite.FormRow;
import com.dodo.blog.ui.component.container.Form;
import com.dodo.blog.ui.component.input.AjaxSubmitButton;
import com.dodo.blog.ui.component.input.Anchor;
import com.dodo.blog.ui.component.input.TextBox;
import com.dodo.blog.ui.page.AbstractPage;

import javax.inject.Inject;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
@Authorized( roles = {Role.ADMIN} )
public class TagEdit
        extends AbstractPage
{
    private static final long serialVersionUID = 1L;

    public static final String TAG_ID = "id";

    private static TagService tagService;

    private static final String TAG_FORM = "tag-form";

    @SetModel( name = TAG_FORM )
    public Response setModel( Tag tag )
    {
        tagService.saveTag( tag );

        return Response.redirect( TagList.class );
    }

    @GetModel( name = TAG_FORM )
    public Tag getModel()
    {
        Long id = getLongParameter( TAG_ID );

        Tag tag;
        if ( id != null )
        {
            tag = tagService.getTagById( id );
        }
        else
        {
            tag = new Tag();
        }

        return tag;
    }

    @Override
    public void onRender()
    {
        setHeader( localize( "header.tagEdit" ) );

        Form form = new Form( TAG_FORM, Tag.class );
        add( form );

        FieldSet fieldSet = new FieldSet( localize( "title.tagEdit" ) );
        form.add( fieldSet );

        fieldSet.add( new FormRow( localize( "label.name" ), new TextBox( "name" ).setAutoFocus( true ) ) );

        form.add( new AjaxSubmitButton( "save", localize( "button.save" ) ) );
        form.add( new Anchor( "cancel", localize( "button.cancel" ), TagList.class ) );
    }

    @Inject
    public void setTagService( TagService tagService )
    {
        TagEdit.tagService = tagService;
    }
}
